package com.vitaf.cash.app.ui.activity

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.graphics.toColorInt
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest
import com.google.android.gms.auth.api.identity.Identity
import com.vitaf.cash.app.R
import com.vitaf.cash.app.base.app.VitafActStackManager
import com.vitaf.cash.app.common.VitafComActV2
import com.vitaf.cash.app.configs.GombeCreditApiPath
import com.vitaf.cash.app.configs.GombeCreditApiUrl
import com.vitaf.cash.app.configs.GombeCreditApiUrl.addCommonParams
import com.vitaf.cash.app.configs.VitafConfigs
import com.vitaf.cash.app.databinding.ActivityLoginBinding
import com.vitaf.cash.app.event.VitafEventPointType
import com.vitaf.cash.app.event.room.VitafPointManager
import com.vitaf.cash.app.request.IHttpCallback
import com.vitaf.cash.app.sdk.analyse.util.GombeCreditGoogleUtil
import com.vitaf.cash.app.utils.SpannableStringUtil
import com.vitaf.cash.app.utils.VitafDateUtil
import com.vitaf.cash.app.utils.VitafTitleBarUtil
import com.vitaf.cash.app.utils.helper.GombeCreditAnalysisHelper
import com.vitaf.cash.app.utils.helper.VitafConfigsHp
import com.vitaf.cash.app.utils.log.VitafLog
import com.vitaf.cash.app.utils.shared.VitafSharedHp
import com.vitaf.cash.app.utils.shared.VitafSharedKey
import com.vitaf.cash.app.weight.input.RobotoMediumInputView
import com.vitaf.cash.lib.adapter.VitafOnSingleClickListener
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:48
 * @Annotation：登录
 */
class VitafUserLoginAct : VitafComActV2() {
    lateinit var binding: ActivityLoginBinding

    override val pageName: String = "Login_Page"

    override fun createVitafContentView(): View {
        binding = ActivityLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initializeVitafViews() {
        binding.loginContentLayout.setPadding(0, VitafTitleBarUtil.getStatusBarHeight(),0,0)
        //关闭所有页面
        VitafActStackManager.finishAllActivity(VitafUserLoginAct::class.java)
        checkGombeCreditLoginBtnState()
    }

    override fun setupVitafEventListeners() {
        //客服
        binding.iconCustomer.setOnClickListener {
            showCustomerDialog()
        }
        binding.textMobile.setOnClickListener (object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.USER_LOGIN_SELF_MOBILE)
                requestGombeCreditPhoneNumber()
            }
        })
        binding.editMobile.setInputFocusChangeListener(object : RobotoMediumInputView.IInputFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                checkGombeCreditLoginBtnState(hasFocus)
            }
            override fun onCompleteAction(v: View?, remark: String?) {
                addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_FORM.LOGIN_MOBILE, remark)
            }
        })
        //电话号码入框监听
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if (takeGombeCreditLoginMobile().isNotEmpty()) {
                    binding.editMobile.setTextColor(getColor(R.color.black))
                }
                checkGombeCreditLoginBtnState(true)
            }
        })
        binding.editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editMobile.clearFocus()
                true
            }
            false
        }

        //隐私政策切换
        binding.loginCheckBox.setOnCheckedChangeListener { _, isChecked ->
            checkGombeCreditLoginBtnState(true)
            when (isChecked) {
                true -> {
                    addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.LOGIN_PRIVACY_AGREE)
                }

                false -> {
                    addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.LOGIN_PRIVACY_DENY)
                }
            }
        }

        //登录
        binding.btnLogin.setOnClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                binding.editMobile.clearFocus()
                addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.LOGIN_NEXT, takeGombeCreditLoginMobile())
                onHideSoftInput(binding.editMobile)
                // TODO: 登录注册点下一步 需上报所有埋点
                VitafPointManager.getInstance().manualReport()

                //登录之前，需要验证手机号是否在 app配置 accList 里存在
                val accItem = checkUserLoginConfigAccount()
                //accList 存在该手机号，直接进入登录成功流程
                if (accItem != null){
                    VitafSharedHp.addGombeCreditSharedData(VitafSharedKey.GOMBECREDIT_IS_CONFIG_ACCOUNT,true)
                    onUserLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
                    return
                }
                doLoginAction()
            }
        })

        //隐私协议
        binding.textLoginPrivacyPolicy.setOnClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                val showTitle = getString(R.string.privacy_policy_title)
                val linkUrl = VitafConfigs.GOMBECREDIT_PRIVACY_POLICY_SENEGAL_LINK
                VitafPrivacyPolicyAct.start(this@VitafUserLoginAct, showTitle, linkUrl)
            }
        })
    }

    @SuppressLint("SetTextI18n")
    override fun loadVitafData() {
        val showZoneCode = "+${VitafSharedHp.takeGombeCreditSharedString(VitafSharedKey.GOMBECREDIT_TIMEZONE_CODE)}"
        val zoneText = SpannableStringUtil.create()
            .setText(showZoneCode)
            .setKey(showZoneCode)
            .setUnderline()
            .complete()
            .build()
        binding.textLoginZoneCode.text = zoneText

        val showPrivacyPolicy = String.format(getString(R.string.login_accept), getString(R.string.privacy_policy_title))
        val ppText = SpannableStringUtil.create()
            .setText(showPrivacyPolicy)
            .setKey(getString(R.string.privacy_policy_title))
            .setColor("#FFFF8378".toColorInt())
            .setUnderline()
            .complete()
            .build()
        binding.textLoginPrivacyPolicy.text = ppText

        binding.editMobile.visibility = View.VISIBLE
        binding.textMobile.visibility = View.VISIBLE
    }

    /**
     * 设置登录按钮状态
     */
    private fun checkGombeCreditLoginBtnState(hasFocus: Boolean = false) {
        if (hasFocus){
            binding.editMobile.setBackgroundResource(R.drawable.vitaf_radius_12_frame_ff15bc62_fill_fff9fafc)
            binding.textMobile.setBackgroundResource(R.drawable.vitaf_radius_12_frame_ff15bc62_fill_fff9fafc)
        } else {
            binding.editMobile.setBackgroundResource(R.drawable.vitaf_radius_12_frame_ffc9c9c9_fill_fff9fafc)
            binding.textMobile.setBackgroundResource(R.drawable.vitaf_radius_12_frame_ffc9c9c9_fill_fff9fafc)
        }
        binding.editMobile.setTextColor(getColor(R.color.black))
        binding.btnLogin.isEnabled = binding.loginCheckBox.isChecked && takeGombeCreditLoginMobile().isNotEmpty()
    }

    /**
     * 获取电话号码
     */
    fun takeGombeCreditLoginMobile(): String {
        return binding.editMobile.text.toString().trim()
    }

    /**
     * 获取本机手机号码
     */
    private fun requestGombeCreditPhoneNumber(){
        val request: GetPhoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder().build()
        Identity.getSignInClient(this)
            .getPhoneNumberHintIntent(request)
            .addOnSuccessListener { result: PendingIntent ->
                try {
                    phoneNumberHintIntentResultLauncher.launch(IntentSenderRequest.Builder(result).build())
                } catch (e: Exception) {
                    VitafLog.e("Launching the PendingIntent failed")
                    showGombeCreditInputMobile()
                }
            }
            .addOnFailureListener {
                VitafLog.e("Phone Number Hint failed : OnFailureListener")
                showGombeCreditInputMobile()
            }
    }

    private val phoneNumberHintIntentResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            var phoneNumber = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.data)
            VitafLog.e(">>>>>>>>>>>>>>>>>>>>>>>Phone Number $phoneNumber")
            addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_FORM.USER_LOGIN_SELF_MOBILE,phoneNumber)
            //时区区号
            val zoneCode = "+${VitafSharedHp.takeGombeCreditSharedString(VitafSharedKey.GOMBECREDIT_TIMEZONE_CODE)}"
            phoneNumber = phoneNumber.replace(zoneCode,"")
            binding.editMobile.setText(phoneNumber)
            binding.editMobile.visibility = View.VISIBLE
            binding.textMobile.visibility = View.GONE
            binding.editMobile.requestFocus()
            binding.editMobile.setSelection(takeGombeCreditLoginMobile().length)
        } catch(e: Exception) {
            VitafLog.e("Phone Number Hint failed：${e.message}")
            addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.USER_LOGIN_SELF_MOBILE_CANCEL,e.message)
            showGombeCreditInputMobile()
        }
    }

    /**
     * 显示手机号码输入框
     */
    private fun showGombeCreditInputMobile(){
        binding.editMobile.visibility = View.VISIBLE
        binding.textMobile.visibility = View.GONE

        lifecycleScope.launch {
            delay(200)
            binding.editMobile.requestFocus()
            onShowSoftInput(binding.editMobile)
            binding.editMobile.setSelection(takeGombeCreditLoginMobile().length) // 将光标设置到文本末尾
        }
    }

    private fun showGombeCreditMainHomePage() {
        onIntent(VitafMainAct::class.java)
        finish()
    }

    /**
     * 登录成功
     */
    private fun onUserLoginSuccess(uid: String, token: String){
        hideVitafLoading()
        //保存手机号码，个人中心使用
        VitafSharedHp.addGombeCreditSharedData(VitafSharedKey.GOMBECREDIT_MOBILE, takeGombeCreditLoginMobile())
        //保存用户登录时间
        val loginTime = VitafDateUtil.getFormatTime(System.currentTimeMillis(),"dd/MM/yyyy HH:mm:ss")
        VitafSharedHp.addGombeCreditSharedData(VitafSharedKey.GOMBECREDIT_LOGIN_TIME,loginTime)
        //保存用户登录状态为已登录
        VitafSharedHp.addGombeCreditSharedData(VitafSharedKey.GOMBECREDIT_LOGIN,true)
        //保存用户id
        VitafSharedHp.addGombeCreditSharedData(VitafSharedKey.GOMBECREDIT_USERID,uid)
        //保存用户Token
        VitafSharedHp.addGombeCreditSharedData(VitafSharedKey.GOMBECREDIT_TOKEN,token)
        //初始化analysis lib 赋值 用户id 和 token
        GombeCreditAnalysisHelper.initAnalysisLibAtLoginSuccess()
        //进入主页
        showGombeCreditMainHomePage()
    }

    /**
     * 获取是否是审核账号信息
     */
    private fun checkUserLoginConfigAccount(): JSONObject?{
        //发送验证码之前，需要验证手机号是否在 app配置 accList 里存在
        val customize = VitafConfigsHp.takeGombeCreditConfigData()
        var accItem: JSONObject? = null
        if (customize != null){
            val accList = customize.optJSONArray("accList")
            if (accList != null && accList.length() > 0){
                for (i in 0..<accList.length()){
                    val obj = accList.optJSONObject(i)
                    if (takeGombeCreditLoginMobile() == obj.optString("accM")){
                        accItem = obj
                        break
                    }
                }
            }
        }
        return accItem
    }

    /**
     * 登录
     */
    private fun doLoginAction(){
        showVitafLoading()
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LOGIN_NO_CODE_PATH)
            put("mobile",takeGombeCreditLoginMobile())//手机号
            put("code","0000")//验证码
            put("channelCode", GombeCreditGoogleUtil.getInstallReferrer())//渠道号
            put("subChannelCode", GombeCreditGoogleUtil.getInstallReferrer())//子渠道号
            put("directLoginFlag","YES")//是否直接登录
            put("notBindWalletFlag","YES")//不自动绑卡
            put("loginParam","")
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    val userId = obj.optString("userId")
                    val userToken = obj.optString("token")
                    val type = obj.optString("type")

                    //是否是渠道用户
                    val isAdSource = obj.optString("isAdSource")
                    if ("YES" == isAdSource){
                        VitafSharedHp.addGombeCreditSharedData(VitafSharedKey.GOMBECREDIT_IS_ADSOURCE,true)
                    }
                    onUserLoginSuccess(userId,userToken)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showVitafToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                hideVitafLoading()
            }
        })
    }
}